package org.mzy.pet.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.mzy.basic.config.BussinessException;
import org.mzy.basic.domain.Point;
import org.mzy.basic.service.impl.BaseServiceImpl;
import org.mzy.basic.util.*;
import org.mzy.order.domain.OrderPetAcquisition;
import org.mzy.order.service.IOrderPetAcquisitionService;
import org.mzy.org.domain.Employee;
import org.mzy.org.domain.Shop;
import org.mzy.org.mapper.EmployeeMapper;
import org.mzy.org.mapper.ShopMapper;
import org.mzy.org.service.IEmployeeService;
import org.mzy.pet.domain.SearchMasterMsg;
import org.mzy.pet.domain.SearchMasterMsgAuditLog;
import org.mzy.pet.dto.AcceptDto;
import org.mzy.pet.mapper.SearchMasterMsgAuditLogMapper;
import org.mzy.pet.mapper.SearchMasterMsgMapper;
import org.mzy.pet.query.SearchMasterMsgQuery;
import org.mzy.pet.service.ISearchMasterMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import sun.plugin2.message.Message;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mzy
 * @since 2022-11-01
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    public IEmployeeService employeeService;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IOrderPetAcquisitionService orderPetAcquisitionService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg) {
        // 0.保存到数据库
        searchMasterMsgMapper.add(searchMasterMsg);
        // 1.参数校验，抽了方法
        this.verify(searchMasterMsg);
        // 2.百度AI审核
        this.baiduVrify(searchMasterMsg);
        // 4.成功，修改状态为已审核
        searchMasterMsg.setState(1);
        // 5.查询50公里以内的最近的店铺，并且给数据店铺赋值，没找到就不管
        // 获取地址的经纬度
        Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
        // shop集合
        List<Shop> shops = shopMapper.findAll();
        // 调用比较距离的方法
        Shop shop = DistanceUtil.getNearestShop(point, shops);
        // 如果不为空，就赋值
        if (shop != null) {
            searchMasterMsg.setShopId(shop.getId());
        }
        // 6.修改数据，返回ajax
        searchMasterMsgMapper.update(searchMasterMsg);
        return AjaxResult.me().success();
    }

    @Override
    public PageList<SearchMasterMsg> queryPage(SearchMasterMsgQuery query) {
        // 查询总条数
        Integer totals = searchMasterMsgMapper.findByCount(query);
        if (null == totals || 0 == totals) {
            return new PageList<>(0, new ArrayList<>());
        }
        // 查询数据
        List<SearchMasterMsg> searchMasterMsgs = searchMasterMsgMapper.findByPage(query);
        return new PageList<>(totals, searchMasterMsgs);
    }

    /*接单*/
    @Override
    public void accept(AcceptDto acceptDto) {
        // 通过前端给的宠物信息Id，获取寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(acceptDto.getMsgId());
        // 参数校验
//        if (searchMasterMsg == null) {
//            throw new BussinessException("无效的寻主消息");
//        }
        // 线程问题
        synchronized (searchMasterMsg.getId()) {
            // 通过前端给的处理人Id获取员工信息
            Employee employee = employeeMapper.findById(acceptDto.getHandler());
            // 参数校验
            if (employee == null) {
                throw new BussinessException("无效的员工信息");
            }
            // 如果寻主信息的状态为1并且寻主信息的店铺Id和员工的店铺Id相同
            if (searchMasterMsg.getState() == 1 && searchMasterMsg.getShopId().equals(employee.getShopId())) {
                // 修改寻主消息状态为2
                searchMasterMsg.setState(2);
                // 更新数据
                searchMasterMsgMapper.update(searchMasterMsg);
                // 生成订单
                this.initOrderPetAcquisition(acceptDto, searchMasterMsg, employee);
//                rocketMQTemplate.asyncSend("pethome_topic", MessageBuilder.withPayload());
            }
        }
    }

    /*拒单*/
    @Override
    public void reject(Long msgId, Employee employee) {
        // 通过前端给的宠物信息Id，获取寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(msgId);
        // 参数校验
        if (searchMasterMsg == null) {
            throw new BussinessException("无效的寻主消息");
        }
        // 修改寻主信息店铺Id为null
        searchMasterMsg.setShopId(null);
        // 更新数据
        searchMasterMsgMapper.update(searchMasterMsg);
        // 添加拒单日志
    }

    /*从寻主池中将信息获取到店铺*/
    @Override
    public void getMessage(AcceptDto acceptDto, Employee employee) {
        // 获取信息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(acceptDto.getMsgId());
        searchMasterMsg.setShopId(employee.getShopId());
        searchMasterMsgMapper.update(searchMasterMsg);
    }

    /*通过*/
    @Override
    public void pass(SearchMasterMsgAuditLog searchMasterMsgAuditLog) {
        SearchMasterMsg msg = new SearchMasterMsg();
        msg.setState(1);
        searchMasterMsgMapper.update(msg);
    }

    private void verify(SearchMasterMsg searchMasterMsg) {
        if (StringUtils.isBlank(searchMasterMsg.getAddress()) || StringUtils.isBlank(searchMasterMsg.getName()) ||
                searchMasterMsg.getGender() == null) {
            throw new BussinessException("审核失败！参数为空！请到个人中心重新填写！");
        }
    }

    private void baiduVrify(SearchMasterMsg searchMasterMsg) {
        StringBuilder sb = new StringBuilder()
                .append(searchMasterMsg.getName())
                .append(searchMasterMsg.getAddress())
                .append(searchMasterMsg.getCoatColor())
                .append(searchMasterMsg.getTitle());
        // 3.失败，添加日志
        if (!BaiduAuditUtils.TextCensor(sb.toString())) {
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            // 生成日志表
            log.setMsgId(searchMasterMsg.getId());
            log.setState(0);
//            log.setAuditId();
            log.setNote("审核失败！内容违规！请到个人中心重新填写！");
            searchMasterMsgAuditLogMapper.add(log);
        }
    }

    /*生成订单*/
    private void initOrderPetAcquisition(AcceptDto acceptDto, SearchMasterMsg searchMasterMsg, Employee employee) {
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        orderPetAcquisition.setOrderSn(CodeGenerateUtils.generateOrderSn(acceptDto.getHandler()));
        orderPetAcquisition.setDigest(acceptDto.getNote());
        orderPetAcquisition.setLastConfirmTime(new Date(System.currentTimeMillis() + 3 * 24 * 60 * 60 * 1000));
        orderPetAcquisition.setState(0);
        // 此時的钱就是用户发布的价格，要注意此金额不是最终金额，要以实际交易金额为准
        orderPetAcquisition.setPrice(new BigDecimal(searchMasterMsg.getPrice()));
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        orderPetAcquisition.setShopId(employee.getShopId());
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setEmpId(employee.getId());
        orderPetAcquisition.setSearchMasterMsgId(searchMasterMsg.getId());
        orderPetAcquisitionService.add(orderPetAcquisition);
    }
}
